<template>
  <div class="pages">
    <Gheader
        style="background: #ebebeb;color: #333333;font-weight: bold;"
        position="center"
        title="任务"
    ></Gheader>
    <div class="pages-content">
      <div id="map" ref="container"></div>
      <div class="dywrapper">
        <div class="dycontent" v-if="showdy">
          <div style="height: 400px;overflow: auto;padding: 10px">
            <div class="dytitle">站点订阅</div>
            <div>
              <van-checkbox-group v-model="result">
                <van-cell-group>
                  <van-cell
                      v-for="(item, index) in detailInfo.taskPassPointList"
                      clickable
                      :key="item.id"
                      :title="`${item.pointName}`"
                      @click="toggle(index)"
                      style="border: 1px solid #E5E7EB;margin-bottom: 5px"
                  >
                    <template #right-icon>
                      <van-checkbox shape="square" :name="item.id" ref="checkboxes" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-checkbox-group>
            </div>
          </div>
          <div class="btnwrapper" style="display: flex">
            <van-button @click="showdy = false" style="margin-right: 10px" class="confirmbtn" block plain type="info">关闭</van-button>
            <van-button :disabled="result.length === 0" @click="subscriptionSave" class="confirmbtn" block plain type="info">确认订阅</van-button>
          </div>
        </div>
        <img class="dybtn" @click="speak" src="../../assets/img/dy.png" alt="">
      </div>
      <div class="event-content" id="eventlist-content-wrapper">
        <div class="eventlist" v-for="i in deviceEventRespList" @click="dialogueMobAudio(i)">
          {{i.eventMessage}}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Gheader from "@/components/Header.vue";
import {wgs84togcj02} from "@/lib/gps";
import {taskGetById, mySubscription, subscriptionSave, dialogueMobAudio} from '@/api/mytask';
import {getuserinfoPromise} from '@/api/myapi'
import start from "@/assets/img/start.png";
import end from "@/assets/img/end.png";
import car from "@/assets/img/car.png";
import {Toast} from "vant";
import moment from 'moment'
export default {
  name: "detail",
  components: {Gheader},
  data() {
    return {
      map: null,
      marker: null,
      socket: null,
      currentDeviceId: '',
      carMarker: null,
      result: [],
      list: ['a', 'b'],
      showdy: false,
      detailInfo: {},
      userInfo: {},
      deviceEventRespList: [],
      audio: null
    }
  },
  methods: {
    dialogueMobAudio(item) {
      var data = moment(item.createdTime).format('YYYY年M月D日 HH:mm:ss') + '即将到达' + item.eventMessage
      if(this.audio) this.audio.pause()
      dialogueMobAudio({text: data}, 'blob').then(res => {
        console.log(res, '000001')
        const blob = new Blob([res], { type: 'audio/wav' });
        const localUrl = (window.URL || webkitURL).createObjectURL(blob);
        if(!this.audio) this.audio = document.createElement('audio');
        this.audio.style.display = 'none'; // 防止影响页面布局
        this.audio.controls = true;
        this.audio.autoplay = true;
        this.audio.muted = true
        document.body.appendChild(this.audio);
        this.audio.src = localUrl;
        this.audio.playbackRate = 1; // 语速
        this.audio.type="audio/wav"
        this.audio.play();

        // 语音播放完毕后，需要手动释放内存
        this.audio.onended = () => {
          document.body.removeChild(this.audio);
          URL.revokeObjectURL(localUrl);
          this.audio = null
          this.$forceUpdate()
        };
      })
    },
    async getuserinfo() {
      const res = await getuserinfoPromise(this.$route.query.openid)
        if(res.code === 0) {
          this.userInfo = res.data || {}
        } else {
          this.userInfo = {}
        }
    },
    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },
    handlerSend(deviceId){
      this.currentDeviceId = deviceId
      // 1.1 先 JSON 化 message 消息内容
      const messageContent = JSON.stringify({
        deviceId: this.currentDeviceId,
        personNum: this.userInfo.cardNum,
        taskId: this.$route.query.id
      })
      // 1.2 再 JSON 化整个消息
      const jsonMessage = JSON.stringify({
        // type: 'demo-message-send',
        type: 'device-message-send',
        content: messageContent
      })
      // 2. 最后发送消息
      this.socket.send(jsonMessage)
    },
    handlerStopSend() {
      if(!this.currentDeviceId) return
      // 1.1 先 JSON 化 message 消息内容
      const messageContent = JSON.stringify({
        deviceId: this.currentDeviceId,
        personNum: this.userInfo.cardNum,
        msgStatus:'stop'
      })
      // 1.2 再 JSON 化整个消息
      const jsonMessage = JSON.stringify({
        type: 'device-message-send',
        content: messageContent
      })
      // 2. 最后发送消息
      this.socket.send(jsonMessage)
    },
    getWebsocket() {
      // 创建WebSocket连接
      this.socket = new WebSocket('ws://ops.nmholdtime.com/reception/infra/ws');
      // 监听连接打开事件
      this.socket.addEventListener('open', () => {
        console.log('WebSocket连接已打开');
      });

      this.socket.addEventListener('message', (data) => {
        const jsonMessage = JSON.parse(data.data)
        const type = jsonMessage.type
        const content = JSON.parse(jsonMessage.content)
        this.deviceEventRespList.push(...content.deviceEventRespList)
        this.refresh()
        console.log('收到消息:', type, content);
        // 2.2 消息类型：demo-message-receive
        if (type === 'device-message-receive') {
          this.currentDeviceId = content.deviceId
          if(this.carMarker) {
            this.carMarker.setPosition(wgs84togcj02(content.deviceLocationNewRespVO.longitude, content.deviceLocationNewRespVO.latitude))
            this.carMarker.setAngle(content.deviceLocationNewRespVO.direction)
          } else {
            this.carMarker = new AMap.Marker({
              map: this.map,
              icon: car,
              position: wgs84togcj02(content.deviceLocationNewRespVO.longitude, content.deviceLocationNewRespVO.latitude),
              anchor:'bottom-center',
              angle: content.deviceLocationNewRespVO.direction
            });
          }
          return
        }
      });

    },
    initMap() {
      if(this.map) {
        return
      }
      this.map = new AMap.Map(this.$refs.container, {
        resizeEnable: true,
        center: [109.95315,40.621327],
        zoom: 14
      });
      this.map.setFitView();
    },
    clearMarker() {
      if (this.marker) {
        this.marker.setMap(null);
        this.marker = null;
      }
    },
    mySubscription() {
      this.result = []
      mySubscription({taskId: this.$route.query.id, personNum: this.userInfo.cardNum}, res => {
        if(res.code === 0) {
          res.data.taskPassPointList.forEach(e => {
            if(e.subscribe) {
              this.result.push(e.id)
            }
          })
          this.$forceUpdate()
        }
      })
    },
    subscriptionSave() {
      if(!this.result.length) return
      console.log(this.result)
      var data = {
        personNum: this.userInfo.cardNum,
        taskId: this.$route.query.id,
        deviceId: this.currentDeviceId,
        pointList: this.result
      }
      subscriptionSave(data, res => {
        if(res.code === 0) {
          Toast('订阅成功')
          this.showdy = false
        }
      })
    },
    getDetail() {
      taskGetById(this.$route.query.id, async res => {
        if(res.code === 0) {
          this.detailInfo = res.data
          const detailInfo = res.data
          await this.getuserinfo()
          this.handlerSend(detailInfo.deviceId)
          let planRouteOLd = detailInfo.planRoute?detailInfo.planRoute.split(';'):[]
          const path = []
          const planRoute = []
          planRouteOLd.forEach(e => {
            let x = wgs84togcj02(...e.split(','))
            path.push(x)
            planRoute.push(x.join(','))
          })
          this.mySubscription()
          setTimeout(() => {
            this.drawLine(path)
            this.getStartAndEndPoint(planRoute, detailInfo)
          }, 1000)
        }
      })
    },
    drawLine (path) {
      if(path.length < 2) return
      const polyline3 = new AMap.Polyline({
        path: path,
        strokeColor: "#25A5F7",
        strokeOpacity: 1,
        strokeWeight: 4,
        strokeStyle: "solid",
      })
      polyline3.setMap(this.map)
      this.map.setFitView([ polyline3 ])
    },
    getStartAndEndPoint (path, value) {
      const departure = {}
      const destination = {}
      if(path.length > 2) {
        departure.location = path[0]
        destination.location = path[path.length - 1]
        departure.address = value.departure || ''
        destination.address = value.destination || ''
        new AMap.Marker({
          map: this.map,
          icon: start,
          position: departure.location.split(','),
          anchor:'bottom-center'
        });
        new AMap.Marker({
          map: this.map,
          icon: end,
          position: destination.location.split(','),
          anchor:'bottom-center'
        });
      }
    },
    speak() {
      this.showdy = !this.showdy
      var msg = new SpeechSynthesisUtterance("您有一条新的预警，");
      window.speechSynthesis.speak(msg);
    },
    refresh() {
      setTimeout(() => {
        const div = document.getElementById('eventlist-content-wrapper');
        div.scrollTo({top:div.scrollHeight - div.clientHeight, behavior:'smooth'});
      }, 100)
    }
  },
  mounted() {
    this.getWebsocket()
    this.initMap()
    this.getDetail()
  },
  beforeDestroy() {
    // 在组件销毁时关闭WebSocket连接
    if (this.socket) {
      this.handlerStopSend()
      this.socket.close();
      this.socket = null
    }
  }
}
</script>

<style scoped lang="less">
.pages {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.pages-content {
  height: calc(100% - 50px);
  overflow: hidden;
  #map {
    width: 100%;
    height: 100%;
  }
}
.dywrapper {
  display: block;
  width: 260px;
  position: absolute;
  bottom: 100px;
  right: 10px;
  background: #ffffff;
  color: #000000;
  border-radius: 6px;
  box-shadow: 0px 4px 6px -4px rgba(0, 0, 0, 0.18), 0px 10px 15px -3px rgba(0, 0, 0, 0.18);
  .btnwrapper {
    padding: 10px;
    .confirmbtn {
      border-radius: 10px;
    }
  }
  .dytitle {
    padding: 10px 0;
  }
  .dybtn {
    position: absolute;
    bottom: -80px;
    right: 10px;
  }
}
.event-content {
  position: absolute;
  bottom: 20px;
  left: 20px;
  width: 100px;
  height: 200px;
  overflow-y: auto;
  overflow-x: hidden;
  .eventlist {
    background: #ffffff;
    padding: 10px;
    text-align: center;
    border-radius: 5px;
    box-shadow: 1px 1px 20px #666;
  }
}
</style>
